package com.ccnf.config;

import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.async.DeferredResult;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * 生成API接口文档的swagger配置类
 */
@Configuration
@EnableSwagger2// 激活SpringFox Swagger2
@EnableSwaggerBootstrapUI
@ConditionalOnProperty(prefix = "swagger", name = "enabled", havingValue = "true")
public class SwaggerConfig {
    @Value("${swagger.enabled}")
    private boolean enabledSwagger;

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)// 配置使用Swagger使用的文档版本
                .genericModelSubstitutes(DeferredResult.class)
                .useDefaultResponseMessages(false)
                .forCodeGeneration(true)
                .pathMapping("/")// 设置API访问时的content-path路径
                .directModelSubstitute(LocalDate.class, String.class)
                .apiInfo(apiInfo())
                .enable(enabledSwagger)
                .select()
                // 指定Swagger的扫描包,假如不指定此项，在Spring Boot项目中，会生成base-err-controller的api接口项
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))//这里采用包含注解的方式来确定要显示的接口
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(security())
                .securityContexts(securityContexts());
//                .globalOperationParameters(defaultTokenHeader());
    }

    /**
     * 设置默认Token参数
     * @return
     */
    private List<Parameter> defaultTokenHeader() {
        ParameterBuilder tokenPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<>();
        tokenPar.name("authorization").description("令牌")
                .modelRef(new ModelRef("string"))
                .parameterType("header").required(false)
                .defaultValue("Please set the token!!!")
                .build();
        pars.add(tokenPar.build());
        return pars;
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("H5邀请函 API接口文档")
                .description("H5邀请函 API接口文档描述")
                .contact(new Contact("会管家", "http://www.ccnf.com", "930168863@qq.com"))
                .termsOfServiceUrl("http://localhost:8085")
                .version("1.0")
                .build();
    }

    private List<ApiKey> security() {
        ArrayList<ApiKey> list = new ArrayList<>();
        list.add(new ApiKey("令牌Token", "authorization", "header"));
        return list;
    }

    private List<SecurityContext> securityContexts() {
        List<SecurityContext> securityContexts=new ArrayList<>();
        securityContexts.add(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        .forPaths(PathSelectors.regex("^(?!auth).*$"))
                        .build());
        return securityContexts;
    }

    List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        List<SecurityReference> securityReferences=new ArrayList<>();
        securityReferences.add(new SecurityReference("令牌Token", authorizationScopes));
        return securityReferences;
    }
}